package cn.zhaoyuening.fanrpc.provider.core;

import cn.zhaoyuening.fanrpc.common.beans.RpcRequest;
import cn.zhaoyuening.fanrpc.common.beans.RpcResponce;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;

import java.util.Map;

public class RpcRequestHandler extends ChannelHandlerAdapter {
    private Map<String, Object> rpcServiceMap;
    private ServiceCallHandler serviceCallHandler = new ServiceCallHandler();

    public RpcRequestHandler(Map<String, Object> rpcServiceMap) {
        this.rpcServiceMap = rpcServiceMap;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (!(msg instanceof RpcRequest)) {
            return;
        }
        RpcRequest request = (RpcRequest) msg;
        RpcResponce rpcResponce = serviceCallHandler.handleRequest(request, rpcServiceMap);
        if (rpcResponce == null) {
            return;
        }
        ctx.write(rpcResponce);
    }
}
